// const beamcoder = require('beamcoder');
const beamcoder = require('D:\\jscode\\beamcoder-master\\build\\Release\\beamcoder.node');

/**
 * 检测mp4文件是否能被beamcoder处理
 * 当前主要是检测：宽是否为8的倍数，如果不是的化，可能会导致beamcoder解析出错。
 * @param videoFile
 * @returns {Promise<boolean>}
 */
async function validate_mp4(videoFile) {
    try {
        let result = await get_mp4_info(videoFile);
        //如果视频的宽度不是8的倍数，beamcoder调用ffmpeg在解析的时候，会自动在每一行塞入对齐数据。
        //最终导致我们拿到rgba去播放的时候，图像显示异常，比如是斜条纹显示
        return result.videoInfo['width'] % 8 === 0;
    }catch (e) {
        console.log(`mp4 file not exits:${videoFile}`);
        return false;
    }
}

/**
 * 获取视频文件的基本信息, 如音频和视频的相关信息
 * 主要信息内容如下所是：
 videoInfo: {
    type: 'CodecParameters', codec_type: 'video', codec_id: 27, name: 'h264', codec_tag: 'avc1',
    format: 'yuv420p', bit_rate: 243194, bits_per_coded_sample: 24, bits_per_raw_sample: 8, profile: 'Constrained Baseline', level: 31,
    width: 582, height: 800, sample_aspect_ratio: [ 0, 1 ], chroma_location: 'left', channel_layout: '0 channels'
  },
 audioInfo: {
    type: 'CodecParameters', codec_type: 'audio', codec_id: 86018, name: 'aac', codec_tag: 'mp4a',
    bit_rate: 65349, bits_per_coded_sample: 16, profile: 'LC', level: -99, sample_aspect_ratio: [ 0, 1 ], chroma_location: 'unspecified', channel_layout: 'mono',
    channels: 1, sample_rate: 48000, frame_size: 1024 }
 }
 * @param videoFile
 * @returns {Promise<{audioInfo: {[p: string]: (() => string) | any | number | string | Buffer | "CodecParameters" | Array<number>}, videoInfo: {[p: string]: (() => string) | any | number | string | Buffer | "CodecParameters" | Array<number>}}>}
 */
async function get_mp4_info(videoFile){
    let demuxer;
    try {
        demuxer = await beamcoder.demuxer(videoFile);
    }catch (e) {
        console.log(`validate mp4 failed:${videoFile}`, e);
        throw 'file not exist';
    }

    let videoStream = demuxer.streams.find(x=>x.codecpar['codec_type']==='video');
    let audioStream = demuxer.streams.find(x=>x.codecpar['codec_type']==='audio');

    let videoInfo = { ...videoStream?.codecpar }
    let audioInfo = { ...audioStream?.codecpar }
    videoInfo =Object.fromEntries(Object.entries(videoInfo).filter(([key,value])=>value!=='unknown' && value!==0));
    audioInfo =Object.fromEntries(Object.entries(audioInfo).filter(([key,value])=>value!=='unknown' && value!==0));
    return { videoInfo, audioInfo };
}

async function main(){
    let result = await validate_mp4('../../media/gh_1.mp4');
    console.log('视频文件检测结果', result);
    result = await validate_mp4('/home/wchi/Desktop/sxh_beamcoder/friends.mp4');
    console.log('视频文件检测结果', result);

    let totalInfo = await get_mp4_info('../../media/gh_1.mp4');
    console.log('获取的音视频信息为', totalInfo);
}
main()

module.exports = {validate_mp4, get_mp4_info}